from flask import Flask
from flask_migrate import Migrate

import commands
import config
from apps import ft_bp, media_bp, cms_bp
from exts import db, mail, cache, csrf, avatars, jwt, cors, socketio

app = Flask(__name__)
app.config.from_object(config)

db.init_app(app)
mail.init_app(app)
cache.init_app(app)
csrf.init_app(app)
avatars.init_app(app)
jwt.init_app(app)
cors.init_app(app, resources={r"/cmsapi/*": {"origins": "*"}})
Migrate(app, db)
socketio.init_app(app, cors_allowed_origins="*", async_mode="eventlet")
# 排除cmsapi的csrf验证
csrf.exempt(cms_bp)

app.register_blueprint(ft_bp)
app.register_blueprint(media_bp)
app.register_blueprint(cms_bp)

app.cli.command("init_board")(commands.init_board)
app.cli.command("init_post")(commands.init_post)
app.cli.command("init_seven_day_post")(commands.init_seven_day_post)
app.cli.command("init_roles")(commands.init_roles)
app.cli.command("bind_roles")(commands.bind_roles)
app.cli.command("init_developer")(commands.init_develpoer)


@app.teardown_appcontext
def teardown_db(exception=None):
    """请求结束后移除 Session"""
    db.session.remove()  # Flask-SQLAlchemy 已封装 scoped_session


if __name__ == '__main__':
    socketio.run(app, host="0.0.0.0")
